package com.lv.common.adapter

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.lv.common.bean.CommonSelectedBean
import java.util.Collections

/**
 * 作者： ygx
 * 创建日期：2023/8/19 3:00 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：
 */
class FactoryContainerPagerAdapter(
    fragmentManager: FragmentManager,
    lifecycle: Lifecycle,
    private val titleList: MutableList<CommonSelectedBean>
) :
    FragmentStateAdapter(fragmentManager, lifecycle) {


    fun addFragment(fragment: Fragment, title: CommonSelectedBean) {
        titleList.add(title)
        notifyDataSetChanged()
    }

    fun removeFragment(element: CommonSelectedBean) {
        titleList.remove(element)
        notifyDataSetChanged()
    }

    fun removeFragment(position: Int) {
        titleList.removeAt(position)
        notifyDataSetChanged()
    }

    fun removeAllFragment() {
        titleList.clear()
        notifyDataSetChanged()
    }

    fun setDatas(titles: MutableList<CommonSelectedBean>) {
        titleList.clear()
        titleList.addAll(titles)
        notifyDataSetChanged()
    }

    fun swapFragments(fromPosition: Int, toPosition: Int) {
//        Collections.swap(fragmentList, fromPosition, toPosition)
        Collections.swap(titleList, fromPosition, toPosition)
        notifyDataSetChanged()
    }

    override fun getItemCount(): Int {
        return titleList.size
    }

    override fun createFragment(position: Int): Fragment {
        return listener?.getFragment(position)!!
    }

    override fun getItemId(position: Int): Long {
        return titleList[position].name.hashCode().toLong()
    }


    fun getPageTitle(position: Int): CharSequence {
        return titleList[position].name ?: ""
    }

    var listener: CirTabListener? = null

    interface CirTabListener {
        fun getFragment(position: Int): Fragment?
    }
}
